import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getUserFromRequest } from '@/lib/auth'

export async function GET(request: NextRequest) {
  try {
    const user = getUserFromRequest(request)
    
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const { searchParams } = new URL(request.url)
    const search = searchParams.get('search') || ''
    const author = searchParams.get('author') || ''
    const hasText = searchParams.get('hasText') || ''
    const dateRange = searchParams.get('dateRange') || ''

    // 构建查询条件（与内容管理页面相同的逻辑）
    const where: any = {}
    
    if (search) {
      where.OR = [
        { title: { contains: search } },
        { description: { contains: search } }
      ]
    }
    
    if (author) {
      where.author = { contains: author }
    }
    
    if (dateRange) {
      const now = new Date()
      let startDate: Date
      
      switch (dateRange) {
        case 'today':
          startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate())
          break
        case 'week':
          startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
          break
        case 'month':
          startDate = new Date(now.getFullYear(), now.getMonth(), 1)
          break
        default:
          startDate = new Date(0)
      }
      
      where.createdAt = { gte: startDate }
    }

    // 获取所有符合条件的视频
    const videos = await prisma.tikTokVideo.findMany({
      where,
      orderBy: { createdAt: 'desc' },
      include: {
        textExtractions: {
          select: {
            extractedText: true,
            confidence: true,
            method: true,
            status: true
          }
        }
      }
    })

    // 根据文案状态筛选
    let filteredVideos = videos
    if (hasText === 'yes') {
      filteredVideos = videos.filter(video => video.textExtractions.length > 0)
    } else if (hasText === 'no') {
      filteredVideos = videos.filter(video => video.textExtractions.length === 0)
    }

    // 生成CSV内容
    const csvHeaders = [
      '视频ID',
      '标题',
      '描述',
      '作者',
      '点赞数',
      '分享数',
      '评论数',
      '播放数',
      '时长(秒)',
      '视频URL',
      '提取的文案',
      '文案置信度',
      '提取方法',
      '采集时间'
    ]

    const csvRows = filteredVideos.map(video => {
      const textExtraction = video.textExtractions[0] // 取第一个文案提取记录
      return [
        video.videoId,
        `"${(video.title || '').replace(/"/g, '""')}"`,
        `"${(video.description || '').replace(/"/g, '""')}"`,
        video.author || '',
        video.likes || 0,
        video.shares || 0,
        video.comments || 0,
        video.views || 0,
        video.duration || 0,
        video.url,
        textExtraction ? `"${textExtraction.extractedText.replace(/"/g, '""')}"` : '',
        textExtraction ? (textExtraction.confidence || 0) : '',
        textExtraction ? textExtraction.method : '',
        new Date(video.createdAt).toLocaleString('zh-CN')
      ].join(',')
    })

    const csvContent = [csvHeaders.join(','), ...csvRows].join('\n')

    // 添加BOM以支持Excel正确显示中文
    const bom = '\uFEFF'
    const csvWithBom = bom + csvContent

    return new NextResponse(csvWithBom, {
      headers: {
        'Content-Type': 'text/csv; charset=utf-8',
        'Content-Disposition': `attachment; filename="tiktok_content_${new Date().toISOString().split('T')[0]}.csv"`
      }
    })

  } catch (error) {
    console.error('Export content error:', error)
    return NextResponse.json(
      { error: '导出失败' },
      { status: 500 }
    )
  }
}
